package com.chat.login.utils;

import com.chat.common.common.constant.MessageConstant;
import com.chat.common.common.exception.RoutineException;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class EmailUtils {

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    public void sendEmail(String to, String subject, String content){

        if (to == null || to.isEmpty()){
            throw new RoutineException(MessageConstant.EMAIL_NOT);
        }

        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(content);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + to);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败：" + e.getMessage());
            throw new RoutineException(MessageConstant.EMAIL_SEND_FAIL);
        }
    }
}
